package com.xca.photogallery.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FastjsonUtils {

   /**
    * 获取assets目录下json文件中的字符串
    * @param context
    * @param fileName 文件名
    * @return
    */
   public static String getJsonFromAssets(Context context, String fileName) {
      //将json数据变成字符串

      StringBuilder stringBuilder = new StringBuilder();
      try {
         //获取assets资源管理器
         AssetManager assetManager = context.getAssets();
         //通过管理器打开文件并读取
         BufferedReader bf = new BufferedReader(new InputStreamReader(
                 assetManager.open(fileName)));
         String line;
         while ((line = bf.readLine()) != null) {
            stringBuilder.append(line);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
      return stringBuilder.toString();
   }

   /**
    * Json字符串转JavaBean
    *
    */
   public static <T> T jsonToObj(String json, Class<T> cls) {
      if (TextUtils.isEmpty(json) || null == cls) return null;
      T t = null;
      try {
         t = JSON.parseObject(json, cls);
      } catch (Exception e) {
         e.printStackTrace();
      }
      return t;
   }

   /**
    * Json转List
    *
    */
   public static <T> List<T> jsonToList(String json, Class<T> cls) {
      if (TextUtils.isEmpty(json) || null == cls) return null;
      List<T> list = new ArrayList<>();
      try {
         list = JSON.parseArray(json, cls);
      } catch (Exception e) {
         e.printStackTrace();
      }
      return list;
   }

   /**
    * 递归获取某个Key对应的值
    * @param jsonStr
    * @param key
    * @return
    */
   public static String getKeyRecursively(String jsonStr, String key) {
      JSONObject json = JSON.parseObject(jsonStr, Feature.OrderedField);
      if (json.containsKey(key)) {
         Log.d("asdf", "key = " + key);
         return json.getString(key);
      }
      for (Map.Entry<String, Object> entry : json.entrySet()) {
         Object value = entry.getValue();
         if (value instanceof JSONObject) {
            JSONObject jo = (JSONObject) value;
            String result = getKeyRecursively(jo.toJSONString(), key);
            if (result != null && !result.isEmpty()) {
               return result;
            }
         }
      }
      return null;
   }
}
